#include "commonusermanagement.h"
#include "ui_commonusermanagement.h"
#include <QMessageBox>
#include <QDebug>

CommonUserManagement::CommonUserManagement(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CommonUserManagement),
    m_userManager(nullptr)
{
    ui->setupUi(this);

    // 设置表头标签
    QStringList headers;
    headers << "用户名" << "密码" << "手机号" << "邮箱" << "昵称" << "用户属性";
    ui->tableWidget->setHorizontalHeaderLabels(headers);
}

CommonUserManagement::~CommonUserManagement()
{
    delete ui;
}

void CommonUserManagement::setUserManager(UserManager* manager)
{
    m_userManager = manager;
    refreshTable();
}

void CommonUserManagement::refreshTable()
{
    if (!m_userManager) {
        qDebug() << "UserManager未初始化";
        return;
    }

    // 清空表格
    ui->tableWidget->setRowCount(0);

    // 通过UserManager执行TCP查询
    QString result = m_userManager->executeUserQuery("SELECT username, password, phone, email, nickname, role FROM users");
    qDebug() << "Raw query result:" << result;
    if (result.startsWith("Error:")) {
        QMessageBox::warning(this, "错误", "获取用户列表失败: " + result);
        return;
    }

    // 解析TCP返回的数据
    QStringList lines = result.split('\n', QString::SkipEmptyParts);
    foreach (const QString &line, lines) {
        QStringList fields = line.split("|", QString::SkipEmptyParts);
        if (fields.size() < 6) continue;

        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row);

        // 设置各列数据
        for (int i = 0; i < 6 && i < fields.size(); ++i) {
            ui->tableWidget->setItem(row, i, new QTableWidgetItem(fields[i].trimmed()));
        }
    }
}
